<template>
  <div class="app-container">
    <div class="filter-container clearfix">
      <el-button v-if="checkPermission(permissionRoles.notice_login_add)" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加公告</el-button>
    </div>
    <el-table ref="table" v-loading="listLoading" :data="list" border stripe style="width: 100%;" height="705">
      <el-table-column label="页签名称" prop="tag" align="center" width="100px"></el-table-column>
      <el-table-column label="公告标题" prop="title" align="center"></el-table-column>
      <el-table-column label="公告内容" prop="show_content" align="center"></el-table-column>
      <el-table-column label="显示排序" prop="sort" align="center" width="70px"></el-table-column>
      <el-table-column label="添加时间" prop="create_dt" align="center" width="140px"></el-table-column>
      <el-table-column label="过期时间" prop="expires_dt" align="center" width="140px"></el-table-column>
      <el-table-column label="大区" prop="srid" align="center" width="70px"></el-table-column>
      <el-table-column label="发行渠道" prop="cpid" align="center" width="70px"></el-table-column>
      <el-table-column align="center" label="操作" width="90px">
        <template slot-scope="scope">
          <el-button v-if="checkPermission(permissionRoles.notice_login_edit)" type="text" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button v-if="checkPermission(permissionRoles.notice_login_del)" type="text" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" :title="textMap[dialogType]" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="页签名称" prop="tag">
          <el-input v-model="dataForm.tag" class="defaut-input" placeholder="填写页签名称" />
        </el-form-item>
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="dataForm.title" class="defaut-input" placeholder="填写公告标题" />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <quillEditor ref="myQuillEditor" v-model="dataForm.content" class="ql-editor"></quillEditor>
        </el-form-item>
        <el-form-item label="大区选择" prop="srid">
          <el-select v-model="dataForm.srid" filterable class="defaut-input" clearable>
            <el-option
              v-for="item in serverRegionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发行渠道" prop="cpid">
          <el-select v-model="dataForm.cpid" filterable multiple class="defaut-input" clearable>
            <el-option
              v-for="item in cpList"
              :key="item.cpid"
              :label="item.cpname + '(' + item.cpid + ')'"
              :value="item.cpid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input v-model="dataForm.sort" class="defaut-input" placeholder="显示排序" />
        </el-form-item>
        <el-form-item label="过期时间" prop="expires_dt">
          <el-date-picker
            v-model="dataForm.expires_dt"
            type="datetime"
            style="width: 50%"
          />
        </el-form-item>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import { deepClone } from '@/utils'
import waves from '@/directive/waves' // 实现点击波浪纹
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import quillEditor from '@/components/QuillEditor'
import { getServerRegionList, getChannelPackageList } from '@/api/ops'
import { handleLoginNotice, getLoginNotice, deleteLoginNotice } from '@/api/gm'

const defaultItem = {
  id: '',
  tag: '',
  title: '',
  content: '',
  srid: '',
  cpid: [],
  expires_dt: new Date(new Date().getTime() + 604800000),
  sort: ''
}
export default {
  name: 'NoticeLogin',
  components: { Pagination, quillEditor },
  directives: { waves },
  data() {
    return {
      permissionRoles: this.$store.state.user.permissionRoles,
      list: [],
      serverRegionList: [],
      cpList: [],
      total: 0,
      listLoading: false,
      dataForm: Object.assign({}, defaultItem),
      rules: {
        srid: [{ required: true, message: '请选择大区', trigger: 'blur' }],
        cpid: [{ required: true, message: '请选择发行渠道', trigger: 'blur' }]
      },
      listQuery: {
        page: 1,
        limit: 200
      },
      dialogVisible: false,
      dialogType: 'new',
      textMap: {
        edit: '编辑',
        new: '新增'
      }
    }
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill
    }
  },
  created() {
    this.getList()
    this.getServerRegionList()
    this.getCpList()
  },
  methods: {
    checkPermission,
    async getList() {
      const query = this.listQuery
      this.listLoading = true
      const res = await getLoginNotice(query)
      this.listLoading = false
      this.list = res.data.items
      this.total = res.data.total
    },
    handleFilter() {
      this.getList()
    },
    handleAdd() {
      this.dataForm = Object.assign({}, defaultItem)
      this.dialogType = 'new'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    async getServerRegionList() {
      const res = await getServerRegionList()
      this.serverRegionList = res.data
    },

    async getCpList() {
      const res = await getChannelPackageList()
      this.cpList = res.data.items
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      scope.row.cpid = scope.row.cpid.split(',')
      this.dataForm = deepClone(scope.row)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === 'edit'
          handleLoginNotice(this.dataForm).then(response => {
            if (response.status) {
              if (isEdit) {
                for (let index = 0; index < this.list.length; index++) {
                  if (this.list[index].id === this.dataForm.id) {
                    this.list.splice(index, 1, Object.assign({}, this.dataForm))
                    break
                  }
                }
              } else {
                this.list.push(response.data)
              }
              this.dialogVisible = false
              this.getList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('你确定要删除此行数据吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteLoginNotice(row.id)
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => { console.error(err) })
    }
  }
}
</script>
<style>
.ql-editor {
  padding: 0;
  width: 80%;
}
</style>
